package com.example.cameraglrender.filter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLUtils;

import com.example.cameraglrender.R;
import com.example.cameraglrender.util.OpenGlUtils;

public class DLUTFilter extends AbstractFBOFilter {
    private int mLutSamplerHandle=-1;
    private int[] mLutTextureId;

    private final Bitmap mBitmap;
    public DLUTFilter(Context mContext) {
        super(mContext, R.raw.dlut_vertex, R.raw.dlut_frag);
        mLutSamplerHandle = GLES20.glGetUniformLocation(mProgramId, "uLutSampler");
        mBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.lut_b);
    }

    @Override
    public void prepare(int width, int height, int x, int y) {
        super.prepare(width, height,x,y);

        mLutTextureId = new int[1];

        OpenGlUtils.glGenTextures(mLutTextureId);

        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mLutTextureId[0]);

        GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, mBitmap, 0);

        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);

    }

    @Override
    public int onDrawFrame(int textureId) {

        //锁定绘制的区域  绘制是从左下角开始的
        GLES20.glViewport(0, 0, mOutputWidth, mOutputHeight);
        //绑定FBO，在FBO上操作
        GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFrameBuffers[0]);

        //使用着色器
        GLES20.glUseProgram(mProgramId);

        //赋值vPosition
        mGlVertexBuffer.position(0);
        GLES20.glVertexAttribPointer(vPosition, 2, GLES20.GL_FLOAT, false, 0, mGlVertexBuffer);
        GLES20.glEnableVertexAttribArray(vPosition);

        //赋值vCoord
        mGlTextureBuffer.position(0);
        GLES20.glVertexAttribPointer(vCoord, 2, GLES20.GL_FLOAT, false, 0, mGlTextureBuffer);
        GLES20.glEnableVertexAttribArray(vCoord);


        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
        //SurfaceTexture 对应 GL_TEXTURE_EXTERNAL_OES 类型
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);
        //赋值vTexture
        GLES20.glUniform1i(vTexture, 0);

        if(mLutSamplerHandle >=0) {
            GLES20.glActiveTexture(GLES20.GL_TEXTURE1);
            GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mLutTextureId[0]);
            GLES20.glUniform1i(mLutSamplerHandle, 1);
        }

        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);

        GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);

        return mFBOTextures[0];
    }

}
